<!-- 设备资产列表 -->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import {
  ElTree,
  ElInput,
  ElDivider,
  ElButton,
  ElMessageBox,
  ElMessage,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem
} from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Write, Detail } from './components'
import { Dialog } from '@/components/Dialog'
import { Delete } from '@element-plus/icons-vue'
import {
  highwayRoadTreeList,
  highwayCityPageDataList,
  busFacilityPageDataList,
  busFacilityDeleteById,
  busFacilitySaveOrUpdate,
  highwayRoadPageDataList,
  roadSystemDataList
} from '@/api/highway'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { eachTree, getFirstNode } from '@/utils/tree'
import { querySearchAsync, restaurants, setContentType, delCommonUsage } from '@/utils/commonUsages'
import {
  accessItOptions,
  onlineStateOptions,
  subclassOptions,
  deviceStatusOptions,
  autoProbeOptions,
  probeTypeOptions
} from '@/assets/data/deviceData'
import { geoOptions } from '@/assets/data/trafficData'
import { useOtherStore } from '@/store/modules/other'
import { SUCCESS_CODE } from '@/constants'
import { sysUserDataList } from '@/api/backstage'

const { t } = useI18n()
const otherStore = useOtherStore()
const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const treeS =
      currentNode.type === 'road' ? { roadId: unref(currentNodeKey) } : { city: currentNode.name }
    const res = await busFacilityPageDataList(
      {
        pageNum: unref(currentPage),
        pageSize: unref(pageSize)
      },
      {
        ...treeS,

        orgId: otherStore.orgId,
        ...unref(searchParams)
      }
    )
    return {
      list: res.data.records || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await busFacilityDeleteById({ id: unref(delId) })
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const userList = ref<any[]>([])
interface CommonIdsType {
  list: any[]
  name: string
  field: string
  label: string
  value: string
}
const commonUsagesIds = reactive<CommonIdsType[]>([
  {
    list: [],
    name: 'category',
    label: '设施大类',
    value: '',
    field: 'categoryId'
  },
  { list: [], name: 'maintenancer', field: 'maintenanceId', value: '', label: '维护单位' },
  { list: [], name: 'owner', field: 'ownerId', value: '', label: '所在科室' },
  { list: [], name: 'electrom', field: 'electromId', value: '', label: '机电设备类型' }
])
const marginR = '15px'
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'field86',
    label: '基本信息',
    search: {
      hidden: true
    },
    form: {
      component: 'Divider'
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'city',
    label: '所属地市',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        props: {
          label: 'city',
          value: 'city',
          key: 'id'
        },
        options: []
      }
    },
    table: {
      minWidth: 100
    }
  },
  {
    field: 'roadId',
    label: '所属路段',
    form: {
      component: 'Select',
      componentProps: {
        props: {
          label: 'roadName',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        options: []
      }
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'road',
    label: '所属路段',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      minWidth: 160
    }
  },
  {
    field: 'pileId',
    label: '所在桩号',
    form: {
      // TODO: 桩号下拉框，树结构

      component: 'TreeSelect',
      componentProps: {
        props: {
          label: 'roadName',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        options: []
      }
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'pile',
    label: '所在桩号',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      minWidth: 160
    }
  },
  {
    field: 'roadSystem',
    label: '所属路端系统',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        clearable: true,
        props: {
          label: 'systemName',
          value: 'systemNo',
          key: 'id'
        }
      },
      optionApi: async () => {
        const res = await roadSystemDataList()
        return res.data
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'lanes',
    label: '探测车道',
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      minWidth: 100
    }
  },
  {
    field: 'category',
    label: '设施大类',
    search: {
      componentProps: {
        style: {
          minWidth: '100px',
          maxWidth: '180px'
        }
      },
      formItemProps: {
        style: {
          marginRight: marginR
        }
      }
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择设施大类',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {
            commonUsagesIds[0].list = restaurants
          },
          focus: () => {
            setContentType(22)
          },
          blur: () => {
            commonUsagesIds[0].list = restaurants
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('category')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    table: {
      minWidth: 160
    }
  },
  {
    field: 'subclass',
    label: '设施小类',
    search: {
      component: 'Select',
      componentProps: {
        style: {
          minWidth: '180px'
        },

        options: subclassOptions,
        clearable: true
      },
      formItemProps: {
        style: {
          marginRight: marginR
        }
      }
    },
    form: {
      component: 'RadioGroup',
      value: 1,
      componentProps: {
        options: subclassOptions
      }
    },
    table: {
      minWidth: 100,
      slots: {
        default: ({ row }: any) => {
          return subclassOptions.find((item) => item.value === row.subclass)?.label || ''
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          const value = data.subclass
          return <span>{subclassOptions.find((item) => item.value === value)?.label}</span>
        }
      }
    }
  },
  {
    field: 'name',
    label: '设备名称',
    search: {
      componentProps: {
        style: {
          minWidth: '100px',
          maxWidth: '180px'
        }
      },
      formItemProps: {
        style: {
          marginRight: '0px'
        }
      }
    },
    table: {
      minWidth: 160
    }
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    search: {
      hidden: true
    },
    table: {
      minWidth: 160
    }
  },
  {
    field: 'geo',
    label: '坐标系',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: geoOptions,
        clearable: true
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'longitude',
    label: '部署位置(经度)',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'latitude',
    label: '部署位置(纬度)',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },

  {
    field: 'status',
    label: '状态',
    search: {
      component: 'Select',
      componentProps: {
        style: {
          minWidth: '200px'
        },
        options: deviceStatusOptions,
        clearable: true
      },
      formItemProps: {
        style: {
          marginRight: marginR
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: deviceStatusOptions,
        clearable: true
      }
    }
  },
  {
    field: 'maintenancer',
    label: '维护单位',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择维护单位',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {
            commonUsagesIds[1].list = restaurants
          },
          focus: () => {
            setContentType(21)
          },
          blur: () => {
            commonUsagesIds[1].list = restaurants
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton
                  type="primary"
                  onClick={() => unref(writeRef)?.saveCommon('maintenancer')}
                >
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'usagerId',
    label: '使用人',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        props: {
          label: 'nickname',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        options: []
      }
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'usager',
    label: '使用人',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'leaderId',
    label: '负责人',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        props: {
          label: 'nickname',
          value: 'id',
          key: 'id'
        },
        filterable: true,
        options: []
      }
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'leader',
    label: '负责人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'purchaseDate',
    label: '采购日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'launchDate',
    label: '首次上线时间',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'productionDate',
    label: '出厂日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'manufacturer',
    label: '制造单位',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'period',
    label: '检定周期(月)',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 1,
      componentProps: {
        min: 0
      }
    },
    table: {
      minWidth: 110
    }
  },
  {
    field: 'lastCheckdate',
    label: '最近检定日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      minWidth: 120
    }
  },
  {
    field: 'nextCheckdate',
    label: '下次检定日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'owner',
    label: '所在科室',
    search: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择所在科室',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {
            commonUsagesIds[2].list = restaurants
          },
          focus: () => {
            setContentType(12)
          },
          blur: () => {
            commonUsagesIds[2].list = restaurants
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('owner')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    table: {
      minWidth: 110
    }
  },
  {
    field: 'field87',
    label: '机电信息',
    search: {
      hidden: true
    },
    form: {
      component: 'Divider'
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'electrom',
    label: '机电设备类型',
    search: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择机电设备类型',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {
            commonUsagesIds[3].list = restaurants
          },
          focus: () => {
            setContentType(14)
          },
          blur: () => {
            commonUsagesIds[3].list = restaurants
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('electrom')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'businessSystem',
    label: '所属业务系统',
    search: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择所属业务系统',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(13)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton
                  type="primary"
                  onClick={() => unref(writeRef)?.saveCommon('businessSystem')}
                >
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'labelname',
    label: '设备标签',
    search: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择设备标签',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(15)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('labelname')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'appSoftware',
    label: '运行应用软件',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'appVersion',
    label: '应用软件版本号',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'appPatchDate',
    label: '最后一次安装补丁时间',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'openService',
    label: '开放服务',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'os',
    label: '操作系统',
    search: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择操作系统',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(16)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('os')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'osVersion',
    label: '系统内核版本',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'osUpdateDate',
    label: '最后一次系统升级时间',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'primaryDns',
    label: '主DNS',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择主DNS',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(23)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton
                  type="primary"
                  onClick={() => unref(writeRef)?.saveCommon('primaryDns')}
                >
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'secondDns',
    label: '备DNS',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择备DNS',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(23)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('secondDns')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'mac',
    label: '设备MAC地址',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'ip',
    label: '设备IP地址',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'port',
    label: '连接端口',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'protocol',
    label: '连接协议',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择备DNS',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(17)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('protocol')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'account',
    label: '访问账号',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'accountPassword',
    label: '账号密码',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'lastConnect',
    label: '最后一次连接时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'autoProbe',
    label: '是否自动探测设备状态',
    search: {
      hidden: true
    },
    form: {
      component: 'RadioGroup',
      value: 0,
      componentProps: {
        options: autoProbeOptions
      }
    },
    table: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          const value = data.autoProbe
          return <span>{autoProbeOptions[value].label}</span>
        }
      }
    }
  },
  {
    field: 'probeType',
    label: '探测方式',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: probeTypeOptions
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'apiUrl',
    label: '获取设备运行状态API路径',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'runstateApi',
    label: '获取设备运行状态监测API',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'runstateRule',
    label: '认定设备运行状态正常的规则',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'responseDataformat',
    label: '获取设备运行状态API调用响应数据格式',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'onlineState',
    label: '运行状态',
    search: {
      hidden: true
    },
    form: {
      component: 'RadioGroup',
      value: 0,
      componentProps: {
        options: onlineStateOptions
      }
    },
    table: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          const value = data.onlineState
          return <span>{onlineStateOptions[value].label}</span>
        }
      }
    }
  },
  {
    field: 'resolution',
    label: '分辨率',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择分辨率',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(18)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton
                  type="primary"
                  onClick={() => unref(writeRef)?.saveCommon('resolution')}
                >
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'nvr',
    label: '所连接NVR',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择分辨率',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(19)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('nvr')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'cpu',
    label: 'CPU',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'memory',
    label: '内存大小',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'disk',
    label: '磁盘大小',
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'switch',
    label: '连接交换机',
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择连接交换机',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: () => {},
          focus: () => {
            setContentType(20)
          },
          blur: () => {}
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon('switch')}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'accessIt',
    label: '准入否',
    search: {
      hidden: true
    },
    form: {
      component: 'RadioGroup',
      value: 0,
      componentProps: {
        options: accessItOptions
      }
    },
    table: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: any) => {
          const value = data.accessIt
          return <span>{accessItOptions[value].label}</span>
        }
      }
    }
  },
  {
    field: 'sortOrder',
    label: '显示排序',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 1,
      componentProps: {
        min: 0
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createUser',
    label: '创建人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateUser',
    label: '修改人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },

  {
    field: 'docid',
    label: '设备附件',
    form: {
      component: 'Upload',
      componentProps: {
        limit: 3,
        action: 'https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15',
        fileList: [
          {
            name: 'element-plus-logo.svg',
            url: 'https://element-plus.org/images/element-plus-logo.svg'
          },
          {
            name: 'element-plus-logo2.svg',
            url: 'https://element-plus.org/images/element-plus-logo.svg'
          }
        ],
        multiple: true,
        onPreview: (uploadFile) => {
          console.log(uploadFile)
        },
        onRemove: (file) => {
          console.log(file)
        },
        beforeRemove: (uploadFile) => {
          return ElMessageBox.confirm(`取消上传 ${uploadFile.name} ?`).then(
            () => true,
            () => false
          )
        },
        // onExceed: (files, uploadFiles) => {
        //   ElMessage.warning(
        //     `The limit is 3, you selected ${files.length} files this time, add up to ${
        //       files.length + uploadFiles.length
        //     } totally`
        //   )
        // },
        slots: {
          default: () => <BaseButton type="primary">点击上传</BaseButton>,
          tip: () => <div class="el-upload__tip">jpg/png</div>
        }
      }
    },
    table: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 200,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <BaseButton type="primary" link onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" link onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" link onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
              <ElDropdown trigger="click" style="line-height: inherit;display: inline">
                {{
                  default: () => {
                    return (
                      <BaseButton type="primary" link class="m-l10px">
                        更多
                      </BaseButton>
                    )
                  },
                  dropdown: () => {
                    return (
                      <ElDropdownMenu>
                        <ElDropdownItem onClick={() => action(row, 'edit')}>
                          检定维护
                        </ElDropdownItem>
                        <ElDropdownItem onClick={() => action(row, 'edit')}>
                          设备更换
                        </ElDropdownItem>
                      </ElDropdownMenu>
                    )
                  }
                }}
              </ElDropdown>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
let currentNode = reactive<any>({})

let departmentList = reactive<any[]>([])
const fetchDepartment = async () => {
  const res = await highwayRoadTreeList()

  if (res.data.length === 0) return
  eachTree(res.data, (v, p) => {
    v[v.type] = v.name
    v[v.type + 'Id'] = v.id

    if (p.type) {
      v[p.type] = p.name
      v[p.type + 'Id'] = p.id
    }
    if (p.highway) {
      v.highway = p.highway
      v.highwayId = p.highwayId
    }
  })
  departmentList = res.data || []
  console.log('departmentList', departmentList)

  const nodeData: any = (res.data.length > 0 && getFirstNode(res.data)) || null
  currentNodeKey.value = nodeData.id || ''
  currentNode = nodeData
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
  getList()
}
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  console.log('currentChange', data)
  if (data.type === 'highway') return
  currentNodeKey.value = data.id
  currentNode = data
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const flag = ref(true)

watch(
  dialogVisible,
  () => {
    flag.value = true

    getHighwayRoadPageDataList()
    getSysUserDataList()
  },
  { once: true }
)

const currentRow = ref<any>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = {
    orgId: otherStore.getOrgId,
    orgName: otherStore.getOrgName || '',
    city: currentNode.city,
    roadId: currentNode.type === 'road' ? currentNode.id : '',
    road: currentNode.type === 'road' ? currentNode.name : ''
  }
  console.log('AddAction', currentRow.value)
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id
  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

let highwayCityList = reactive([])
/** 路段列表 */
let RoadPileList = reactive<any[]>([])

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  for (let i = 0; i < commonUsagesIds.length; i++) {
    const item = commonUsagesIds[i]
    if (row[item.field] && row[item.name]) {
      item.value = row[item.field]
    }
  }
  const a = {
    orgId: otherStore.getOrgId,
    orgName: otherStore.getOrgName || ''
  }
  currentRow.value = Object.assign(row, a)
  console.log('action', currentRow.value)
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      // 路段
      if (formData.roadId) {
        formData.road = RoadPileList.find((item) => item.id === formData.roadId)?.roadName || ''
      }
      // 使用人
      if (formData.usagerId) {
        formData.usager =
          userList.value.find((item) => item.id === formData.usagerId)?.nickname || ''
      }
      //   负责人
      if (formData.leaderId) {
        formData.leader =
          userList.value.find((item) => item.id === formData.leaderId)?.nickname || ''
      }

      for (let i = 0; i < commonUsagesIds.length; i++) {
        const item = commonUsagesIds[i]
        if (formData[item.name] && !item.value) {
          const find = item.list.find((i) => i.content === formData[item.name])
          if (find) {
            formData[item.field] = find.id
          } else {
            saveLoading.value = false
            return ElMessage.error(`${item.label} 的id不存在，请先存储再重新选择`)
          }
        }
      }
      console.log('保存提交', formData)
      formData.projectId = otherStore.getProjectId

      const res = await busFacilitySaveOrUpdate(formData)
      if (res) {
        currentPage.value = 1
        saveLoading.value = false
        dialogVisible.value = false
        getList()
      }
    } catch (error) {
      console.log(error)
    }
  }
}

/** 获取所属城市列表 */
const getHighwayCityPageDataList = async () => {
  const res = await highwayCityPageDataList({ pageNum: 1, pageSize: 9999 }, {})
  if (!res || !res.data || !res.data.records) {
    return []
  }
  const formNode = allSchemas.formSchema.find((item) => item.field === 'city')
  highwayCityList = res.data.records || []

  if (formNode) {
    formNode.componentProps.options = highwayCityList
  }
}

/** 获取所属路段列表 */
const getHighwayRoadPageDataList = async () => {
  const res = await highwayRoadPageDataList({ pageNum: 1, pageSize: 9999 }, {})
  if (!res || !res.data || !res.data.records) {
    return []
  }
  const formNode = allSchemas.formSchema.find((item) => item.field === 'roadId')
  RoadPileList = res.data.records || []

  if (formNode) {
    formNode.componentProps.options = RoadPileList
  }
}
/** 获取人员；列表 */
const getSysUserDataList = async () => {
  const res = await sysUserDataList({ orgId: otherStore.getOrgId })
  if (!res || !res.data) {
    return []
  }
  const formNode = allSchemas.formSchema.find((item) => item.field === 'usagerId')
  const formNode1 = allSchemas.formSchema.find((item) => item.field === 'leaderId')
  userList.value = res.data || []

  if (formNode) {
    formNode.componentProps.options = userList.value
  }
  if (formNode1) {
    formNode1.componentProps.options = userList.value
  }
}

const ElTreeProp = {
  children: 'children',
  label: 'name',
  value: 'id',
  disabled: (node) => {
    return node.type !== 'road'
  }
}
getHighwayCityPageDataList()
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <ElInput v-model="currentDepartment" class="flex-[2]" placeholder="路段" clearable />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="ElTreeProp"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      />
    </ContentWrap>
    <ContentWrap class="flex-[1]">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        :operationAdd="true"
        :operation-del="false"
        @add="AddAction"
        @batch-del="delData"
      />

      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%" maxHeight="80vh">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
